<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Bill\Controllers;


use App\Eloquent\Ygt\BillLog;
use App\Eloquent\Ygt\BillWage;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\SellerBill;
use App\Eloquent\Ygt\WarehouseBill;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class LogController extends Controller
{
	public $userId          = 25;
	public function index(){}
	public function lists()
	{
		$userId             = Func::getHeaderValueByName('userid',$this->userId);
		$userInfo           = DepartmentUser::getCurrentInfo($userId);
		$type               = request('type',0);//1支出,2收入
		$billCategoryId     = request('bill_category_id',0);
		$billAccountId      = request('bill_account_id',0);
		$billBuyerId        = request('bill_buyer_id',0);
		$year               = request('year',0);
		$month              = request('month',0);
		$day                = request('day',0);
		$minMoney           = request('min_money',0);
		$maxMoney           = request('max_money',0);
		$remark             = request('remark',0);
		if( !$userInfo )
		{
			xThrow( ERR_PARAMETER );
		}
		$companyId          = $userInfo->company_id;
		$where              = ['ygt_bill_log.company_id'=>$companyId];
		if($type)
		{
			$where['ygt_bill_log.type']  = $type;
		}
		if($billCategoryId)
		{
			$where['ygt_bill_log.bill_category_id']  = $billCategoryId;
		}
		if($billAccountId)
		{
			$where['ygt_bill_log.bill_account_id']   = $billAccountId;
		}
		if($billBuyerId)
		{
			$where['ygt_bill_log.bill_buyer_id']   = $billBuyerId;
		}
		if($minMoney && $maxMoney){
			$moneyArr           = [$minMoney,$maxMoney];
			$where['ygt_bill_log.money']        = ['between',$moneyArr];
		}else if($minMoney && !$maxMoney){
			$where['ygt_bill_log.money']        = ['>',$minMoney];
		}else if(!$minMoney && $maxMoney){
			$where['ygt_bill_log.money']        = ['<',$maxMoney];
		}
		if($remark)
		{
			$where['ygt_bill_log.remark']       = ['like',$remark];
		}
		//月份
		$nowTime            = $_SERVER['REQUEST_TIME'];
		$nowYear            = date('Y',$nowTime);
		$nowMonth           = date('n',$nowTime);
		$year               = $year ? $year : $nowYear;
		$month              = $month ? $month : $nowMonth;
		if($day){
			$startTime          = $year.'-'.$month.'-'.$day;
			$startTimeInt       = strtotime($startTime);
			$endTimeInt         = $startTimeInt + 3600*24;
		}else{
			$startTime          = $year.'-'.$month.'-1';
			$monthTimeInt       = strtotime($startTime);
			$monthDays          = date('t',$monthTimeInt);
			$startTimeInt       = strtotime($startTime);
			$endTimeInt         = $startTimeInt + 3600*24*$monthDays;;
		}
		$timeArr            = [$startTimeInt,$endTimeInt];
		$where['ygt_bill_log.created_at']    = ['between',$timeArr];
		$searchArr          = [
			'type'=>$type,
			'bill_category_id'=>$billCategoryId,
			'bill_account_id'=>$billAccountId,
			'bill_buyer_id'=>$billBuyerId,
			'year'=>$year,
			'month'=>$month,
			'day'=>$day,
			'min_money'=>$minMoney,
			'max_money'=>$maxMoney,
			'remark'=>$remark,
		];

		$limit              = $offset = '';
		$lists              = BillLog::getListDetail($where,$limit,$offset);

		$inTypeArr          = BillLog::getTypeList('in');//收入类型数组
		$outTypeArr         = BillLog::getTypeList('out');//支出类型数组
		$listMoneyIn        = $listMoneyOut = $listMoneyRemain = 0;
		foreach($lists as $key=>$val)
		{
			if(in_array($val['type'],$inTypeArr)){
				$listMoneyIn    += $val['money'];
                $tempType       = 1;
			}else{
				$listMoneyOut   += $val['money'];
                $tempType       = 2;
			}
			//$lists[$key]['type']    = $tempType;
		}
		$listsGroup         = collect($lists)->groupBy('day_week')->toArray();
		$listsResult        = [];
		foreach($listsGroup as $key=>$val)
		{
			$keyArr         = explode(',',$key);
			$day            = $keyArr[0];
			$week           = $keyArr[1];
			$data           = $val;
			$temp           = [
				'day'=>$day,'week'=>$week,'data'=>$data
			];
			$listsResult[]  = $temp;
		}
		$listMoneyRemain    = $listMoneyIn - $listMoneyOut;
		$listsArr           = [
			'year'=>$year,
			'month'=>$month.'月',
			'money_in'=>$listMoneyIn,
			'money_out'=>$listMoneyOut,
			'money_remain'=>$listMoneyRemain,
		];
		//收入
		$moneyIn            = BillLog::whereIn('type',$inTypeArr)->sum('money');
		//支出
		$moneyOut           = BillLog::whereIn('type',$outTypeArr)->sum('money');
		$moneyRemain        = $moneyIn - $moneyOut;
		$topArr             = [
			'money_in'=>$moneyIn,
			'money_out'=>$moneyOut,
			'money_remain'=>$moneyRemain,
		];
		$result             = [
			'lists'=>$listsResult,
			'lists_arr'=>$listsArr,
			'top_arr'=>$topArr,
			'search_arr'=>$searchArr
		];
		return $result;
	}
	public function nearest()
	{
		$userId             = Func::getHeaderValueByName('userid',$this->userId);
		$userInfo           = DepartmentUser::getCurrentInfo($userId);
		if( !$userInfo )
		{
			xThrow( ERR_PARAMETER );
		}
		$companyId          = $userInfo->company_id;

		$where              = ['company_id'=>$companyId];
		$info               = BillLog::getInfo($where);
		if(!$info)
		{
			$result             = [
				'lists'=>[],
				'lists_arr'=>[
                    'ym_text'=> '',
                    'day_text'=> '',
                    'week_text'=> '',
                    'money_in'=> 0,
                    'money_out'=> 0,
                    'money_remain'=> 0,
                ],
				'top_arr'=>[
                    'money_in'=>0,
                    'money_out'=>0,
                    'money_remain'=>0,
                    'mark_tips' => "今日还没有记账",
                ],
			];
			return $result;
		}
		$infoArr            = $info->toArray();
		$weekArr            = BillLog::getWeekTextArr();
		$nowTime            = $_SERVER['REQUEST_TIME'];
		$nowYear            = date('Y',$nowTime);
		$nowMonth           = date('n',$nowTime);
		$nowDay             = date('j',$nowTime);
		//$nowWeek            = date('N',$nowTime);
		$nowYmdNumber       = $nowYear.$nowMonth.$nowDay;

		$createdAt          = $infoArr['created_at'];
		$infoYear           = date('Y',$createdAt);
		$infoMonth          = date('n',$createdAt);
		$infoDay            = date('j',$createdAt);
		$infoWeek           = date('N',$createdAt);
		$infoYmdNumber      = $infoYear.$infoMonth.$infoDay;
		$ymText             = $nowYear.'.'.$nowMonth;
		$dayText            = $nowDay;
		$weekText           = $weekArr[$infoWeek];
		if($nowYmdNumber==$infoYmdNumber)
		{
			$dayText        = '今日';
		}
		$startTime          = $infoYear.'-'.$infoMonth.'-'.$infoDay;
		$startTimeInt       = strtotime($startTime);
		$where              = ['ygt_bill_log.company_id'=>$companyId];
		$where['ygt_bill_log.created_at']   = ['>',$startTimeInt];
		$limit              = $offset = '';
		$lists              = BillLog::getListDetail($where,$limit,$offset);
		$inTypeArr          = BillLog::getTypeList('in');//收入类型数组
		$outTypeArr         = BillLog::getTypeList('out');//支出类型数组
		$listMoneyIn        = $listMoneyOut = $listMoneyRemain = 0;
		foreach($lists as $key=>$val)
		{
			if(in_array($val['type'],$inTypeArr)){
				$listMoneyIn    += $val['money'];
			}else{
				$listMoneyOut   += $val['money'];
			}

		}
		$listMoneyRemain    = $listMoneyIn - $listMoneyOut;
		$listsArr           = [
			'ym_text'=>$ymText,
			'day_text'=>$dayText,
			'week_text'=>$weekText,
			'money_in'=>$listMoneyIn,
			'money_out'=>$listMoneyOut,
			'money_remain'=>$listMoneyRemain,
		];
		//收入
		$moneyIn            = BillLog::whereIn('type',$inTypeArr)->sum('money');
		//支出
		$moneyOut           = BillLog::whereIn('type',$outTypeArr)->sum('money');
		$moneyRemain        = $moneyIn - $moneyOut;

		//判断当日记账数量
        $curDayTime = strtotime(date('Ymd'));
        $where = [
            ['created_at','>',$curDayTime]
        ];
        $curDayBillCount = \App\Eloquent\Ygt\BillLog::where($where)->get()->count();
        if($curDayBillCount){
            $markTips = '今日已记账'.$curDayBillCount.'笔';
        }else{
            $markTips = '今日还没有记账';
        }

		$topArr             = [
			'money_in'=>$moneyIn,
			'money_out'=>$moneyOut,
			'money_remain'=>$moneyRemain,
            'mark_tips' => $markTips,
		];
		$result             = [
			'lists'=>$lists,
			'lists_arr'=>$listsArr,
			'top_arr'=>$topArr,
		];
		return $result;
	}
	public function edit()
	{
		$userId             = Func::getHeaderValueByName('userid',$this->userId);
		$userInfo           = DepartmentUser::getCurrentInfo($userId);
		if( !$userInfo )
		{
			xThrow( ERR_PARAMETER );
		}
		$companyId              = $userInfo->company_id;
		$data                   = request()->all();
		$type                   = request('type',0);
		$typeName               = request('type_name','');//wb=>WarehouseBill
		$tableId                = request('type_id',0);
        $warehouseBillId        = request('warehouse_bill_id',0);////////////为了兼容!!!!!!!!!
		$customerId             = 0;
		if($type==4 && $warehouseBillId>0){
            $tableId            = $warehouseBillId;
            $typeName           = 'wb';
        }
        if(in_array($type,[3,4]) && !$tableId)
        {
            xThrow( ERR_PARAMETER );
        }
        $typeNameArr            = [
            'wb'=>'warehouse_bill','u'=>'user','sell'=>'seller_bill'
        ];
		$tableName              = isset($typeNameArr[$typeName]) ? $typeNameArr[$typeName] : '';
		if($tableName=='warehouse_bill'){
			$where              = ['id'=>$tableId];
            $typeInfo           = WarehouseBill::getInfo($where);
			if($typeInfo){
				$customerId     = $typeInfo->customer_id;
			}else{
                xThrow( ERR_PARAMETER );
            }
		}else if($tableName=='user'){
			$month              = request('month',0);
			$year               = request('year',0);
			$where              = ['year'=>$year,'month'=>$month,'user_id'=>$tableId];
			$typeInfo           = BillWage::getInfo($where);
            if($typeInfo){
                $isUpdate       = true;
            }else{
                $isUpdate       = false;
            }
		}else if($tableName=='seller_bill'){
            $where              = ['id'=>$tableId];
            $typeInfo           = SellerBill::getInfo($where);
            if(!$typeInfo)
            {
                xThrow( ERR_UNKNOWN,'该账单不存在,或者信息有误' );
            }
            if($typeInfo->status==1)
            {
                xThrow( ERR_UNKNOWN,'该账单已经结清了' );
            }
        }

		$data['company_id']     = $companyId;
		$data['table']          = $tableName;
		$data['table_id']       = $tableId;
		$data['customer_id']    = $customerId;
		$fieldList              = BillLog::$tableFieldList;
		$tableData              = BillLog::setDataByTableField($data,$fieldList);
		$tableDataCheckResult   = BillLog::checkDataByTableField($tableData,$fieldList);
		if($tableDataCheckResult !== true)
		{
			xThrow(ERR_PARAMETER, $tableDataCheckResult);
		}
		$editResult             = BillLog::editData($tableData);
		if($editResult===false)
		{
			xThrow(ERR_UNKNOWN);
		}
		//账单核收的时候,必须是支出类型,这时需要修改对应的应收单
		$requestMoney           = request('money',0);
		if($tableName=='warehouse_bill'){
			$nowMoney           = $typeInfo->now_money;
			$warehouseBillId    = $typeInfo->id;
			if($nowMoney > 0)
			{
				$nowMoney       = $nowMoney - $requestMoney;
				$where          = ['id'=>$warehouseBillId];
				$data           = ['now_money'=>$nowMoney];
				if($nowMoney<0 || $nowMoney==0)
				{
                    $data       = ['now_money'=>0,'status'=>1];
				}
				WarehouseBill::updateOneData($where,$data);
			}
		}else if($tableName=='user'){
            if($isUpdate){
                $where              = ['year'=>$year,'month'=>$month,'user_id'=>$tableId];
                $infoMonyPay        = $typeInfo->mony_pay;
                $monyPay            = $requestMoney + $infoMonyPay;
                $data               = ['mony_pay'=>$monyPay];
                BillWage::updateOneData($where,$data);
            }else{
                $data               = [
                    'company_id'=>$companyId,
                    'year'=>$year,
                    'month'=>$month,
                    'user_id'=>$tableId,
                    'mony_pay'=>$requestMoney
                ];
                BillWage::insertOneData($data);
            }
		}else if($tableName=='seller_bill'){
            $nowMoney           = $typeInfo->now_money;
            $typeId             = $typeInfo->id;
            if($nowMoney > 0)
            {
                $nowMoney       = $nowMoney - $requestMoney;
                $where          = ['id'=>$typeId];
                $data           = ['now_money'=>$nowMoney];
                if($nowMoney<0 || $nowMoney==0)
                {
                    $data       = ['now_money'=>0,'status'=>1];
                }
                SellerBill::updateOneData($where,$data);
            }
        }
		$result         = ['message'=>'编辑成功'];
		return $result;
	}
	public function typeList()
	{
		$result             = BillLog::getTypeList();
		return $result;
	}
	public function detail()
	{
		$userId             = Func::getHeaderValueByName('userid',$this->userId);
		$userInfo           = DepartmentUser::getCurrentInfo($userId);
		$id                 = request('id',0);
		if(!$userInfo || !$id)
		{
			xThrow( ERR_PARAMETER );
		}
		$companyId              = $userInfo->company_id;
		$where                  = ['company_id'=>$companyId,'id'=>$id];
		$info                   = BillLog::getInfo($where);
		if(!$info)
		{
			xThrow(ERR_UNKNOWN);
		}
		$result         = $info->toArray();
		return $result;
	}
}